// pages/commodityDetail/commodityDetail.js
var app = getApp()
var util = require('../../utils/util.js')
var api = require('../../utils/api.js')
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		bannerUrls: [],
		payNum: 1,
		systemModel: app.globalData.isIphoneX,
		isIphone: app.globalData.isIphone,
		authStatus: '', //授权显示
		expressNum: '', //运费
		allMoney: 0, //结算价钱
		isLoad: true,
		isAddress: false, //地址取消授权后的打开设置按钮
		payStatus: true, //是否能付款
		video_url: '',
		sale: [{
				title: '正品保障',
				img: '../../images/pledge.png'
			},
			{
				title: '七天退款',
				img: '../../images/refund.png'
			},
			{
				title: '售后无忧',
				img: '../../images/sale.png'
			}
		],
		sale_info: [{
			text: '   1、本商品售后概要，如果商品存在质量问题均可申请退款，非质量问题申请退款的商品，需自理运费；'
		}, {
			text: '2、平台提供商品采购清单，商品均可提供相关资料，方便您了解商品。'
		}, {
			text: '3、凡在商城购买的商品，商城方提供发货物流信息，如果无法获取物流信息，可联系客服人员进行查询。'
		}],
		refund_info: [{
			text: '      第一步：在【我的】页面点击联系客服，留言：”客服”注明退款原因等待客服人员审核；'
		}, {
			text: '第二步：客服人员审核无误后，系统将会办理退款流程，办理成功后金额将会退至原账户中；'
		}, {
			'text': '注意事项：申请退款过程中，如有任何疑问可联系客服咨询。'
		}],
		money: '',
		time: '',
		commentList:{
			title:true,
			blank:false,
			show:true,
			gid:'',
			list:[]
		},
		redData:'',
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		let redData = ''
		if(wx.getStorageSync('redData')){
			redData = JSON.parse(wx.getStorageSync('redData'))
		}
		
		let that = this
		that.setData({
			isLoad: true,
			red_id: options.red_id || '',
			width: wx.getSystemInfoSync().screenWidth,
			isIphoneX: app.globalData.isIphoneX,
			authStatus: app.globalData.authStatus || false,
			gid: options.gid,
			redData:redData
		})
		if(that.data.redData.end_time){
			that.countTime()
		}
		this.getDetail()
	},
	// 商品详情
	getShopDetail: function(gid) {
		let that = this
		let data = {
			gid: gid,
		}
		console.log(999, data, wx.getStorageSync('uid'))
		if (that.data.red_id) {
			data.red_id = that.data.red_id
		}
		api.goodDetail({
			data: data,
			success: res => {
				let bannerUrls = {}
				if (res.data.result.data.cover.indexOf(',')) {
					bannerUrls = res.data.result.data.cover.split(',')
				} else {
					bannerUrls.push(res.data.result.data.cover)
				}
				if (res.data.result.data.explain_imgs) {
					res.data.result.data.explain_imgs = res.data.result.data.explain_imgs.split(',')
				}
				if (res.data.result.data.size) {
					res.data.result.data.count = res.data.result.data.size[0].quantity
					res.data.result.data.size_name = res.data.result.data.size[0].properties_name
					res.data.result.data.price_money = res.data.result.data.size[0].price
				}
				if (res.data.result.data.type == 3 && res.data.result.data.is_yz_edit == 1) {
					let width = app.globalData.screenWidth - 30
					let explain = res.data.result.data.explain.replace(/\<img/g, `<img style="width:${width}px;display:block" `)
					explain = explain.replace(/\height=/g, ' ')
					explain = explain.replace(/\" sty/g, ' ')
					res.data.result.data.explain = explain
				}
				wx.setNavigationBarTitle({
					title: res.data.result.data.name,
				})
				let size = that.data.size
				let sizeList = res.data.result.data.size
				if (!that.data.sizeList) {
					for (let i in sizeList) {
						if (sizeList[i].size_url) {
							sizeList[i].size_url.split(',')
						}
						if (sizeList[i].quantity != 0 && !size) {
							sizeList[i].select = true
							size = sizeList[i]
						}
					}

				} else {
					sizeList = that.data.sizeList
				}
				if (res.data.result.red_packet.use_end_time) {
					that.data.end_time = res.data.result.red_packet.use_end_time
				}

				that.setData({
					size: size,
					sizeList: sizeList,
					authStatus: app.globalData.authStatus,
					goodDetail: res.data.result.data,
					bannerUrls: bannerUrls,
					gid: gid,
					expressNum: res.data.result.data.express_cost,
					isLoad: false,
					red_packet: res.data.result.red_packet,
					redPacketStatus: res.data.result.red_packet.id ? true : false,
					url: res.data.result.data.video_url || '',
					play_video: res.data.result.data.video_url ? true : false,
				})
				if (res.data.result.data.video_url) {
					that.play_video()
				}
				that.allMoneyNum()
				// if (res.data.result.red_packet.use_end_time) {
				// 	that.setData({
				// 		redData:res.data.result.red_packet
				// 	})
				// 	that.countTime()
				// }
				//加载评论
				that.getCommentList()


			}
		})
	},
	getDetail:function(){
		let that=this
		if (!app.globalData.loginStatus) {
			//使用es6的promise进行异步处理
			let promise = new Promise(function(resolve, reject) {
				util.getLogin(resolve)
			});
			promise.then(function() {
				that.setData({
					authStatus: app.globalData.authStatus
				})
				that.getShopDetail(that.data.gid)
			})

		} else {
			that.getShopDetail(that.data.gid)
		}
	},
	//播放视频
	play_video: function() {
		let url = this.data.url
		this.setData({
			video_url: url,
			play_video: false
		})
	},
	end_video() {
		this.setData({
			video_url: '',
			play_video: true
		})
	},
	//倒计时
	countTime() {
		var that = this;
		that.setData({
			loadingtime: setInterval(function() {
				var date = new Date();
				var now = date.getTime();
				var endDate = (that.data.redData.end_time).replace(/-/g, "/");
				endDate = new Date(endDate); //设置截止时间
				var end = endDate.getTime();
				var leftTime = end - now; //时间差                              
				var d, h, m, s, ms;
				h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
				m = Math.floor(leftTime / 1000 / 60 % 60);
				s = Math.floor(leftTime / 1000 % 60);
				ms = Math.floor(leftTime % 10);
				ms = ms < 100 ? ms : ms
				s = s < 10 ? "0" + s : s
				m = m < 10 ? "0" + m : m
				h = h < 10 ? "0" + h : h
				let time = {
					h: h,
					m: m,
					s: `${s}.${ms}`,
				}
				if (leftTime > 0) {
					that.setData({
						time: time
					})
				}
			}, 100)
		})
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		// let that = this
		// let red_packet = wx.getStorageSync('red_packet')
	
		// if (red_packet) {
		// 	that.setData({
		// 		red_packet: red_packet ? red_packet : ""
		// 	})
		// 	that.allMoneyNum()
		// 	wx.removeStorageSync('red_packet')
		// }

		// // if (red_packet.use_end_time) {
		// // 	that.countTime()
		// // }
		// if (!app.globalData.loginStatus) {
		// 	//使用es6的promise进行异步处理
		// 	let promise = new Promise(function(resolve, reject) {
		// 		util.getLogin(resolve)
		// 	});
		// 	promise.then(function() {
		// 		that.setData({
		// 			authStatus: app.globalData.authStatus
		// 		})
		// 		that.getShopDetail(that.data.gid)
		// 	})

		// } else {
		// 	that.getShopDetail(that.data.gid)
		// }
		if(this.data.time){
			this.getDetail()
		}
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {
		clearInterval(this.data.loadingtime)
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {
		let userName = app.globalData.userInfo.uname;
		let shopName = this.data.goodDetail.name
		let imageUrl = this.data.bannerUrls[0]
		let gid = this.data.gid
		return {
			title: '推荐你超低价抢购' + shopName,
			path: `pages/index/index?jump=../commodityDetail/commodityDetail&gid=${gid}`,
			imageUrl: imageUrl,
			success: function(res) {},
			fail: function(res) {
				// 转发失败
			}
		}
	},
	//获取列表
	getCommentList: function(params) {
		return true
		wx.request({
			url: 'https://api.meizhuang.whudong.cn/go/api/comment/commentlist', //仅为示例，并非真实的接口地址
			data: {
				gid: this.data.gid,
				
				page: 1,
			},
			header: {
				'content-type': 'application/json' // 默认值
			},
			success:(res) =>{
				try{
					let list = res.data.data.list;
					for(let i in list){
						list[i].create_time = util.formatTime2(list[i].create_time,'Y-M-D h:m');
						list[i].images = list[i].images.split(',')
						// list[i].text = list[i].text.split("\n").join("&hc")
					}
					this.setData({
						['commentList.list']:list,
						['commentList.gid']:this.data.gid,
					})
				}catch(e){
					console.log(e)
				}
			}
		})
	},
	//立即购买按钮
	promptlyPay: function(e) {

		if(app.globalData.wxshouquan==false){
			console.log("未授权");
			this.getUserProfile()
		}else{
			console.log("已授权");
			var that = this;
		// util.saveFromId(e.detail.formId)
		that.setData({
			payWindows: true
		})
		that.allMoneyNum()
		that.showPayWindows()
		}
		
	},
	// 打开购买动画
	showPayWindows: function(e) {
		var that = this;
		var animation = wx.createAnimation({
			duration: 300,
			timingFunction: 'linear',
			delay: 0
		})
		that.animation = animation;
		animation.translateY(-220).step();
		that.setData({
			upMenuAction: animation.export()
		})
	},
	// 关闭购买动画
	closePayWindows: function(e) {
		var that = this;
		var animation = wx.createAnimation({
			duration: 300,
			timingFunction: 'linear',
			delay: 0
		})
		that.animation = animation;
		animation.translateY(220).step();
		that.setData({
			upMenuAction: animation.export()
		})
	},
	//输入框事件
	payNumber: function(e) {
		let payNum = this.data.payNum
		if (e.detail.value > 98 || e.detail.value > this.data.size.quantity) {
			util.showToast('超过能购买的数量了~', 'none')
			this.setData({
				payNum: 1
			})
		} else {
			this.setData({
				payNum: parseInt(e.detail.value)
			})
			this.allMoneyNum()
		}
	},
	//减少商品
	subtraction: function() {
		if (this.data.payNum > 1) {
			this.setData({
				payNum: this.data.payNum - 1
			})
			this.allMoneyNum()
		} else {
			wx.showToast({
				title: '商品数量不能少于1',
				icon: 'none'
			})
		}
	},
	//加商品
	add: function() {
		let lastNum = this.data.payNum
		if (this.data.payNum > this.data.size.quantity - 1 || this.data.payNum > 98) {
			util.showToast('超过能购买的数量了~', 'none')
			this.setData({
				payNum: lastNum
			})
		} else {
			this.setData({
				payNum: Number(this.data.payNum) + 1
			})
			this.allMoneyNum()
		}
	},
	//结算价钱
	allMoneyNum: function() {
		let that = this

		let allMoney = Number(that.data.payNum) * Number(that.data.size.price) + Number(that.data.expressNum)
		if (that.data.redPacketStatus) {
			allMoney = (allMoney - that.data.red_packet.money).toFixed(2);
		} else {
			allMoney = allMoney.toFixed(2);
		}
		that.setData({
			allMoney: allMoney != 0 ? allMoney : allMoney,
			money: that.data.red_packet.money
		})
	},
	//输入框失去焦点
	payAllNum: function(e) {
		let payNum = this.data.payNum
		if (e.detail.value.length == 0) {
			util.showToast('最少购买数量为1~', 'none')
			this.setData({
				payNum
			})
			this.allMoneyNum()
		}
		if (e.detail.value == 0) {
			util.showToast('最少购买数量为1~', 'none')
			this.setData({
				payNum: 1
			})
			this.allMoneyNum()
		}
	},
	//关闭购买窗口
	popClose: function() {
		this.setData({
			payWindows: false
		})
		this.closePayWindows()
	},
	//预览图片
	prviewPhoto: function(e) {
		let that = this
		let src = that.data.goodDetail.explain_imgs[e.currentTarget.dataset.index]
		util.previewPhoto(src, that.data.goodDetail.explain_imgs)
	},
	// 授权方法
	// bindGetUserInfo(e) {
	// 	let that = this
	// 	if (e && e.detail.userInfo) {
	// 		let userInfo = {
	// 			signature: e.detail.signature,
	// 			encryptedData: e.detail.encryptedData,
	// 			iv: e.detail.iv,
	// 			code: app.globalData.code,
	// 		}
	// 		util.saveUserInfo(that, userInfo)
	// 	}
	// },
	//选择标签
	selectSize: function(e) {
		let sizeList = this.data.sizeList,
			index = e.currentTarget.dataset.index,
			size
		for (let i in sizeList) {
			if (index == i) {
				sizeList[i].select = true
				size = sizeList[i]
			} else {
				sizeList[i].select = false
			}
		}
		this.setData({
			sizeList,
			size
		})
		this.allMoneyNum()
	},
	//选择地址
	chooseAddress(e) {
		let that = this
		// util.saveFromId(e.detail.formId)
		var nowTime = new Date();
		if (nowTime - that.data.payTime < 1000) {
			return;
		}
		that.setData({
			'payTime': nowTime
		});
		wx.getSetting({
			success(res) {
				if (!(JSON.stringify(res.authSetting) == '{}')) {
					if (res.authSetting['scope.address']) {
						// 获取地址
						wx.chooseAddress({
							success: res => {
								let addressInfo = {
									userName: res.userName,
									telNumber: res.telNumber,
									address: res.provinceName + res.cityName + res.countyName + res.detailInfo
								}
								that.setData({
									addressInfo: addressInfo,
									allAddress: res,
								})
							}
						})
					} else if (res.authSetting['scope.address'] == false) {
						that.setData({
							isAddress: true
						});
						that.popClose()
					} else {
						wx.chooseAddress({
							success: res => {
								let addressInfo = {
									userName: res.userName,
									telNumber: res.telNumber,
									address: res.provinceName + res.cityName + res.countyName + res.detailInfo
								}
								that.setData({
									addressInfo: addressInfo,
									allAddress: res,
								})
							}
						})
					}
				} else {
					wx.chooseAddress({
						success: res => {
							let addressInfo = {
								userName: res.userName,
								telNumber: res.telNumber,
								address: res.provinceName + res.cityName + res.countyName + res.detailInfo
							}
							that.setData({
								addressInfo: addressInfo,
								allAddress: res,
							})
						}
					})
				}
			},
			fail: res => {
				util.showToast('保存失败', 'none')
			}
		})
	},
	// 去授权设置页
	popSet: function(e) {
		let that = this
		that.setData({
			isAddress: false
		});
		setTimeout(function() {
			that.promptlyPay()
		}, 1000)
	},
	// 地址弹窗取消
	popCancel: function(e) {
		let that = this
		that.setData({
			isAddress: false
		});
		that.promptlyPay()
	},
	// 地址弹窗取消
	popCancel1: function(e) {
		let that = this
		that.setData({
			isAddress: false
		});
		that.promptlyPay()
	},
	//下拉刷新
	onPullDownRefresh: function() {
		let that = this
		api.goodDetail({
			data: {
				gid: that.data.gid,
			},
			success: res => {
				let bannerUrls = {}
				if (res.data.result.data.cover.indexOf(',')) {
					bannerUrls = res.data.result.data.cover.split(',')
				} else {
					bannerUrls.push(res.data.result.data.cover)
				}
				if (res.data.result.data.explain_imgs) {
					res.data.result.data.explain_imgs = res.data.result.data.explain_imgs.split(',')
				}
				if (res.data.result.data.size) {
					res.data.result.data.count = res.data.result.data.size[0].quantity
					res.data.result.data.size_name = res.data.result.data.size[0].properties_name
					res.data.result.data.price_money = res.data.result.data.size[0].price
				}
				if (res.data.result.data.type == 3 && res.data.result.data.is_yz_edit == 1) {
					let width = app.globalData.screenWidth - 30
					let explain = res.data.result.data.explain.replace(/\<img/g, `<img style="width:${width}px;display:block" `)
					explain = explain.replace(/\height=/g, ' ')
					explain = explain.replace(/\" sty/g, ' ')
					res.data.result.data.explain = explain
				}
				that.setData({
					goodDetail: res.data.result.data,
					bannerUrls: bannerUrls,
					// gid: gid,
					expressNum: res.data.result.data.express_cost,
					isLoad: false,
					red_packet: res.data.result.red_packet,
					redPacketStatus: res.data.result.red_packet.id ? true : false
				})
				wx.stopPullDownRefresh();

			}
		})
	},
	//立即购买付款
	getPay: function(e) {
		
		let that = this
		let address
		let formid = e.detail.formId
		let payStatus = that.data.payStatus
		console.log(formid, payStatus);
		that.setData({
			payStatus: false
		})
		if (payStatus) {
			if (!that.data.addressInfo) {
				util.showToast('请先选择地址~', 'none')
				that.setData({
					payStatus: true
				})
			} else {
				address = {
					"province": that.data.allAddress.provinceName,
					"city": that.data.allAddress.cityName,
					"county": that.data.allAddress.countyName,
					"addressDetail": that.data.allAddress.detailInfo,
					"recipients": that.data.allAddress.userName,
					"tel": that.data.allAddress.telNumber,
					"postalCode": that.data.allAddress.postalCode,
				}
				
				let payList=[
					"91Oa5VmRjJRUcBH9tU3WcvvTHS3eiXpDO2NcJrBe1Jc",
					"MbxrM3kiLdJlkzWJuWOrgPUwZsCcnRxju8Z8RS_AkxI",
					"y0Agf0UHpeLLnB0F1207DHU86RvGoWae4-wnZZbjg74"]
					wx.requestSubscribeMessage({
						tmplIds: payList,
						success:(res)=>{
							let data = {
								gid: that.data.gid,
								num: that.data.payNum,
								address: JSON.stringify(address),
								sku_id: that.data.size.sku_id
							}
							if (that.data.red_packet.id) {
								data.red_id = that.data.red_packet.id
							}
			
							this.subScribe(data)
						},
						fail(res) {let data = {
							gid: that.data.gid,
							num: that.data.payNum,
							address: JSON.stringify(address),
							sku_id: that.data.size.sku_id
						}
						if (that.data.red_packet.id) {
							data.red_id = that.data.red_packet.id
						}
		
						this.subScribe(data)},
						complete:(err)=>{
						  console.log('授权',err)
						}
					  })
				
			}
			complete:()=>{
				this.subScribe(data)
				console.log(11111);
			}
		}
	},
	//订阅信息
	subScribe: function(data) {
		let list = ['SDjUFu8ESGxPAm35GRRs2bk9pNluqY3IT4JsLlqg6oo', 'rZOkc1VjhR_qkBlES8xMN7-efQBAiO2NJwJJF5JOjtA',
			'a1lM1bUy3ftC8-tbVyJ1GBOwVYkYtig1fI_oKfthY0s'
		]
		try {
			wx.requestSubscribeMessage({
				tmplIds: list,
				success(res) {},
				fail(res) {},
				complete: res => {
					console.log(1, res)
					this.payment(data)
				}
			})
		} catch (e) {
			console.log(1, e)
			wx.showToast({
				title: '由于你的微信不是最新版本，将无法收到中奖通知。',
				icon: 'none',
				duration: 3000
			})
		}
	},

	//拉起支付
	payment(data) {
	
		let that = this;
		api.exchange_goods({
			data: data,
			success: res => {
				that.setData({
					payStatus: true
				})
				if (res.data.code == 0) {
					if (res.data.result) {
						if (res.data.result.code != 0) {
							util.showToast(res.data.result.tips)
						} else {
							wx.requestPayment({
								timeStamp: res.data.result.timeStamp,
								nonceStr: res.data.result.nonceStr,
								package: res.data.result.package,
								signType: res.data.result.signType,
								paySign: res.data.result.paySign,
								success(res) {
									wx.navigateTo({
										url: '../paySuccess/paySuccess',
									})
									that.setData({
										payStatus: true
									})
								
								},
								fail(res) {
									util.showToast('支付失败', 'none')
									that.setData({
										payStatus: true
									})
								}
							})
						}
					}
				}
			}
		})

	},

	getRedPacket: function() {
		wx.navigateTo({
			url: `../myRedPacket/myRedPacket?gid=${this.data.gid}&id=${this.data.red_packet.id}`
		})
	},
	get_complain() {
		wx.navigateTo({
			url: '../complaint/complaint',
		})
	},

	getuserinfo(e) {
		let that = this
		if (e && e.detail.userInfo) {
			let userInfo = {
				signature: e.detail.signature,
				encryptedData: e.detail.encryptedData,
				iv: e.detail.iv,
				code: app.globalData.code,
			}
			util.saveUserInfo(that, userInfo).then(res => {
				that.getShopDetail(that.data.gid)
			}).catch(err => {
				console.log(err)
			})
		} else {
			that.setData({
				authStatus: false
			})
		}
	},
	getUserProfile: function(e) {
		
		let This = this;
		console.log('触发了')
		wx.getUserProfile({
			desc: '用于展示用户个人信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
			success: (res) => {
				var app=getApp()
				app.globalData.wxshouquan=true
				if (res.errMsg == "getUserProfile:ok") { //授权成功
					//授权解密的信息
					let params = {
						encryptedData: res.encryptedData,
						iv: res.iv,
						signature: res.signature,
						openid: This.data.userInfo.openid,
						code: This.data.userInfo.code,
					};
					util.saveUserInfo(This, params).then(res => {
						if(!This.data.options.all){
							util.showToast('领取成功,正在跳转', 'none')
						}
						//使用es6的promise进行异步处理
						let promise = new Promise(function(resolve, reject) {
							util.getLogin(resolve)
						});
						promise.then(res => {
							This.getGoodList(1,1,'')
							setTimeout(()=>{
								if (This.data.red_id) {
									// userInfo.red_id = This.data.red_id
									This.useHb(params)
								}
							},800)
						})
					}).catch(err => {
					    console.log(err)
					})
				} else { //取消授权
					utils.showToast('授权失败', 'none');
				}
			},
			complete:(err)=>{
				console.log('授权',err)
			}
		})
	},
	//支付后订阅消息
	reqSubMessage:function(e){
		console.log("支付");
		let payList=[
			"91Oa5VmRjJRUcBH9tU3WcvvTHS3eiXpDO2NcJrBe1Jc",
			"MbxrM3kiLdJlkzWJuWOrgPUwZsCcnRxju8Z8RS_AkxI",
			"y0Agf0UHpeLLnB0F1207DHU86RvGoWae4-wnZZbjg74"]
			wx.requestSubscribeMessage({
				tmplIds: payList,
				success:(res)=>{},
				fail(res) {},
				complete:(err)=>{
				  console.log('授权',err)
				}
			  })
	}
})
